package priv.lhy.ecm.basic.service.dict;

import com.alibaba.dubbo.config.annotation.Service;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import priv.lhy.common.utils.JsonUtil;
import priv.lhy.ecm.basic.constants.BasicResponseCode;
import priv.lhy.ecm.basic.dto.dict.DictCoreRequest;
import priv.lhy.ecm.basic.dto.dict.DictCoreResponse;
import priv.lhy.ecm.basic.dto.dict.DictQueryRequest;
import priv.lhy.ecm.basic.dto.dict.DictQueryResponse;
import priv.lhy.ecm.basic.entity.dict.Dictionaryinfo;
import priv.lhy.ecm.basic.entity.dict.Dictionarytype;
import priv.lhy.ecm.basic.exception.BasicException;
import priv.lhy.ecm.basic.mapper.dict.DictionaryTypeMapper;
import priv.lhy.ecm.basic.mapper.dict.DictionaryinfoMapper;
import priv.lhy.ecm.basic.util.ResponseUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: lihy
 * date: 2019/4/10 17:33
 * description:
 */
@Service(interfaceClass = IDictionaryinfoService.class)
@Component  //上面使用了dubbo的@Service，没有使用spring的@service，所以用@Component将其声明为spring服务
public class DictionaryinfoServiceImpl implements IDictionaryinfoService {

    @Autowired
    private DictionaryinfoMapper infoMapper;

    @Autowired
    private DictionaryTypeMapper typeMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 增加字典信息
     *
     * @param request
     * @return
     */
    @Override
    public DictCoreResponse addDictionaryinfo(DictCoreRequest request) {
        DictCoreResponse response = new DictCoreResponse();
        try {
            long did = infoMapper.insert(request.getInfo());
            if (did > 0) {
                ResponseUtil.getResponse(response, BasicResponseCode.SUCCESS);
            } else {
                ResponseUtil.getResponse(response, BasicResponseCode.SYS_PARAM_NOT_RIGHT);
            }
        } catch (Exception e) {
            throw new BasicException(BasicResponseCode.SYSTEM_BUSY.getCode(), BasicResponseCode.SYSTEM_BUSY.getMsg(), request);
        }
        return response;
    }

    @Override
    public DictQueryResponse getDictionaryinfo(DictQueryRequest request) {
        return null;
    }

    /**
     * 根据字典类型获取字典信息
     *
     * @param request
     * @return
     */
    @Override
    public DictQueryResponse getDictionaryinfosByType(DictQueryRequest request) {
        DictQueryResponse response = new DictQueryResponse();
        //先从redis中获取
        String dictinfoStr = redisTemplate.opsForValue().get("DICT:" + request.getDtid());
        List<Dictionaryinfo> infoList;
        if (null == dictinfoStr) {  //redis中不存在则到数据库获取
            infoList = infoMapper.getDicts(" and dtid=" + request.getDtid(), "desc");
            if (null != infoList && infoList.size() > 0) {  //数据库取到数据则更新redis并返回
                try {
                    redisTemplate.opsForValue().set("DICT:" + request.getDtid(), JsonUtil
                            .Object2Json(infoList));
                    ResponseUtil.getResponse(response, BasicResponseCode.SUCCESS);
                    response.setData(infoList);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                ResponseUtil.getResponse(response, BasicResponseCode.SYS_PARAM_NOT_RIGHT);
            }
        } else {    //redis中有数据则将数据转换成list返回
            try {
                infoList = JsonUtil.json2GenericObject(dictinfoStr,
                        new TypeReference<List<Dictionaryinfo>>() {
                        });
                ResponseUtil.getResponse(response, BasicResponseCode.SUCCESS);
                response.setData(infoList);
            } catch (IOException e) {
                ResponseUtil.getResponse(response, BasicResponseCode.SYS_PARAM_NOT_RIGHT);
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 获取所有字典类型及信息，用于初始化redis
     *
     * @return
     */
    public Map<Dictionarytype, List<Dictionaryinfo>> getInitDict() {
        Map<Dictionarytype, List<Dictionaryinfo>> map = new HashMap<>();
        List<Dictionarytype> typeList = typeMapper.allDictTypes();
        for (Dictionarytype type : typeList) {
            List<Dictionaryinfo> infoList = infoMapper.getDicts(String.format(" and dtid=%d", type.getDtid()), "desc");
            if (null != infoList && infoList.size() > 0) {
                map.put(type, infoList);
            }
        }
        return map;
    }

    public List<Dictionaryinfo> getAllDict(){
        return infoMapper.getDicts("", "desc");
    }
}
